// pages/goods/list/index.js
import { reqGoodsList } from '../../../../../api/good'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [], // 商品列表数据
    isLoading: false,
    isFinish: false, // 判断数据是否加载完毕
    total: 0,
    // 接口请求参数
    requestData: {
      page: 1, // 页码
      limit: 10, // 每页请求多少条数据
      category1Id: '', // 一级分类 id
      category2Id: '' // 二级分类 id
    }
  },

  onLoad(options) {
    Object.assign(this.data.requestData, options)
    this.getList()
  },

  // 获取列表数据
  async getList() {
    if (this.data.isLoading) return
    this.setData({ isLoading: true })
    const { data } = await reqGoodsList(this.data.requestData)
    this.setData({
      goodsList: [...this.data.goodsList, ...data.records],
      total: data.total
    })
    this.setData({ isLoading: false })
  },

  // 上拉加载更多
  onReachBottom() {
    // 判断是否加载完全部数据
    const { goodsList, total } = this.data
    if (goodsList.length === total) {
      this.setData({
        isFinish: true
      })
      return
    }
    let { page } = this.data.requestData
    this.setData({
      "requestData.page": page + 1
    })
    this.getList()
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      "requestData.page": 1,
      goodsList: []
    })
    this.getList()
    wx.stopPullDownRefresh()
  }
})
